<?php
// +----------------------------------------------------------------------
// | OneKeyAdmin [ Believe that you can do better ]
// +----------------------------------------------------------------------
// | Copyright (c) 2020-2023 http://onekeyadmin.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: MUKE <513038996@qq.com>
// +----------------------------------------------------------------------
namespace app\admin\controller;

use app\api\model\CouponLog;
use think\facade\View;
use think\exception\ValidateException;
use app\admin\BaseController;
use app\admin\model\Coupon as CouponModel;
use app\admin\validate\Coupon as Validate;
/**
 * Coupon管理
 */
class Coupon extends BaseController
{
    /**
     * 显示资源列表
     */
    public function index()
    {
        if ($this->request->isPost()) {
            try {
                $input = input("post.");
                validate(Validate::class)->scene("index")->check($input);
            } catch ( ValidateException $e ) {
                return json(["status" => "error", "message" => $e->getError()]);
            }
            $input = input("post.");
            $count = CouponModel::withSearch(["keyword"], $input)->count();
            $data  = CouponModel::withSearch(["keyword"], $input)->with('merchant')->order($input["prop"], $input["order"])->page($input["page"], $input["pageSize"])->select();
            return json(["status" => "success", "message" => "请求成功", "data" => $data, "count" => $count]);
        } else {
            return View::fetch();
        }
    }
    
    /**
     * 保存新建的资源
     */
    public function save()
    {
        if ($this->request->isPost()) {
            try {
                $input = input("post.");
                validate(Validate::class)->scene("save")->check($input);
            } catch ( ValidateException $e ) {
                return json(["status" => "error", "message" => $e->getError()]);
            }
            CouponModel::create($input);
            return json(["status" => "success", "message" => "添加成功"]);
        }
    }
    
    /**
     * 保存更新的资源
     */
    public function update()
    {
        if ($this->request->isPost()) {
            try {
                $input = input("post.");
                validate(Validate::class)->scene("update")->check($input);
            } catch ( ValidateException $e ) {
                return json(["status" => "error", "message" => $e->getError()]);
            }
            CouponModel::update($input);
            return json(["status" => "success", "message" => "修改成功"]);
        }
    }
    
    /**
     * 删除指定资源
     */
    public function delete()
    {
        if ($this->request->isPost()) {
            try {
                $input = input("post.");
                validate(Validate::class)->scene("delete")->check($input);
            } catch ( ValidateException $e ) {
                return json(["status" => "error", "message" => $e->getError()]);
            }
            CouponModel::destroy($input["ids"]);
            return json(["status" => "success", "message" => "删除成功"]);
        }
    }
    /**
     * 自定义更多方法...
     */
    public function publish(){
        $input = input("post.");
        $input['id']=1;
        $coupon=(new CouponModel())->where('id',$input['id'])->findOrEmpty()->toArray();
        if($coupon['status']==1){
            return json(["status" => "error", "message" =>'优惠券已发布请勿重新发布']);
        }
        if(date('Y-m-d H:i:s')>$coupon['end_time']){
            return json(["status" => "error", "message" =>'优惠券已失效']);
        }
        $saveData=[
            'coupon_id'=>$coupon['id'],
            'merchant_id'=>$coupon['merchant_id'],
            'start_time'=>$coupon['start_time'],
            'end_time'=>$coupon['end_time'],
            'amount'=>$coupon['amount'],
            'status'=>0,
        ];
        $this->insertCodes($saveData,$coupon['number']);
        (new CouponModel())->where('id',$input['id'])->update(['status'=>1]);
        return json(["status" => "success", "message" => "发布成功"]);
    }
    private function generateUniqueCode($length = 12) {
        $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
        $charactersLength = strlen($characters);
        $randomString = '';
        for ($i = 0; $i < $length; $i++) {
            $randomString .= $characters[rand(0, $charactersLength - 1)];
        }
        return $randomString;
    }

    public function insertCodes($saveData,$count = 10) {
        for ($i = 0; $i < $count; $i++) {
            $code = $this->generateUniqueCode();
            while (true) {
                try {
                    $saveData['qr_sign']=$code;
                    (new CouponLog())->insert($saveData);
                    break; // 成功插入，跳出循环
                } catch (\Exception $exception) {
                    // 重复，重新生成
                    $code =$this->generateUniqueCode();
                }
            }
        }
    }
}